package com.xinyue.game.center.business.role;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xinyue.game.center.business.account.AccountService;
import com.xinyue.game.center.business.role.manager.RoleCreateManager;
import com.xinyue.game.center.business.role.param.CreateRoleRequest;
import com.xinyue.game.center.business.role.param.CreateRoleResponse;
import com.xinyue.game.center.common.GameCenterConfig;
import com.xinyue.game.center.common.GameTokenService;
import com.xinyue.game.center.dao.entity.AccountEntity;
import com.xinyue.game.center.dao.entity.PlayerEntity;
import com.xinyue.game.center.dao.entity.ZoneRoleEntity;
import com.xinyue.game.jwt.GameRoleToken;

/**
 * @author 王广帅
 * @since 2022/1/16 15:04
 */
@Service
public class RoleService {

    private Logger logger = LoggerFactory.getLogger(RoleService.class);
    @Autowired
    private AccountService accountService;
    @Autowired
    private RoleCreateManager createRoleManager;
    @Autowired
    private GameCenterConfig centerConfig;
    @Autowired
    private GameTokenService gameTokenService;


    public CreateRoleResponse createRole(CreateRoleRequest createRoleParam) throws Exception {
        AccountEntity accountEntity = accountService.getAndCheckAccount(createRoleParam.getUserId());
        createRoleManager.checkNicknameSensitive(createRoleParam.getNickname());
        createRoleManager.checkRoleExist(accountEntity, createRoleParam.getZoneId());
        PlayerEntity roleEntity = createRoleManager.createRole(createRoleParam);
        ZoneRoleEntity zoneRoleEntity = createRoleManager.getZoneRole(roleEntity);
        accountEntity.getSectionPlayerMap().put(createRoleParam.getZoneId(), zoneRoleEntity);
        accountService.updateAccount(accountEntity);
        CreateRoleResponse createRoleResponse = new CreateRoleResponse();
        createRoleResponse.setPlayerId(zoneRoleEntity.getPlayerId());
        createRoleResponse.setNickname(roleEntity.getNickname());
        createRoleResponse.setCreateTime(roleEntity.getCreateTime());
        createRoleResponse.setLastLoginTime(roleEntity.getCreateTime());
        String token = this.createToken(roleEntity);
        createRoleResponse.setToken(token);
        return createRoleResponse;
    }

    private String createToken(PlayerEntity playerEntity) {
        GameRoleToken gameToken = new GameRoleToken();
        gameToken.setPlayerId(playerEntity.getPlayerId());
        gameToken.setUserId(playerEntity.getUserId());
        gameToken.setZoneId(playerEntity.getZoneId());
        String roleToken = gameTokenService.createRoleToken(gameToken);
        return roleToken;
    }

}
